package com.yuanqi.dz.dc.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import pnbclient.helper.StringHelper;
import pnbclient.util.PnbLogFactory;
import pnblog.PnbLogging;

import com.yuanqi.dz.dc.util.DZConfigRead;
import com.yuanqi.dz.dc.util.FtpUtil;
import com.yuanqitech.advancedpower.powerdate.DateUtil;
import com.yuanqitech.advancedpower.powerdate.PowerDateFormat;
import com.yuanqitech.powermop.dz.DZDataInterface;
import com.yuanqitech.powermop.dz.DZInfo;
import com.yuanqitech.powermop.dz.DZInfoArray;

public class SMXICBCDZSerivceImpl  implements DZDataInterface{
	public static final PnbLogging LOG = PnbLogFactory.getLogger("DZ_EXT_LOG");

	private static String fileName = "{date}中国工商银行特约单位POS交易清单171351010013_000.csv";

	public DZInfoArray getDZData(String mercharnum, String dzDate) {
		DZInfoArray  dzInfoArray=new DZInfoArray();
		String is_private=DZConfigRead.getProperties("is_private");
		String source_type=null;
		String address=null;
		String local_path =null;
		String dz_date_format=null;
		String dz_date_addday=null;
		String ftp_port =null;
		String username=null;
		String password = null;
		String remotePath =null;
		String charset = null;
		String start_row = null;
		if(null!=is_private && "0".equals(is_private)){
			String  is_private_mercharnum=DZConfigRead.getProperties("is_private_"+mercharnum);
			if(null!=is_private_mercharnum && is_private_mercharnum.equals("1")){
				source_type=DZConfigRead.getProperties("source_type_"+mercharnum);
				address=DZConfigRead.getProperties("ftp_ip_"+mercharnum);
				local_path=DZConfigRead.getProperties("local_path_"+mercharnum);
				//fileName=DZConfigRead.getProperties("fileName_"+mercharnum);
				dz_date_format=DZConfigRead.getProperties("dz_date_format_"+mercharnum);
				dz_date_addday=DZConfigRead.getProperties("dz_date_addday_"+mercharnum);
				ftp_port=DZConfigRead.getProperties("ftp_port_"+mercharnum);
				username=DZConfigRead.getProperties("ftp_username_"+mercharnum);
				password=DZConfigRead.getProperties("ftp_password_"+mercharnum);
				remotePath=DZConfigRead.getProperties("ftp_filepath_"+mercharnum);
				charset = DZConfigRead.getProperties("charset_"+mercharnum);
				start_row = DZConfigRead.getProperties("start_row_"+mercharnum);
			}else{
				source_type=DZConfigRead.getProperties("source_type");
				address=DZConfigRead.getProperties("ftp_ip");
				local_path=DZConfigRead.getProperties("local_path");//本地目录
				//fileName=DZConfigRead.getProperties("fileName");// 文件名称
				dz_date_format=DZConfigRead.getProperties("dz_date_format");//对账文件时间格式
				dz_date_addday=DZConfigRead.getProperties("dz_date_addday");  
				ftp_port=DZConfigRead.getProperties("ftp_port");
				username=DZConfigRead.getProperties("ftp_username");
				password=DZConfigRead.getProperties("ftp_password");
				remotePath=DZConfigRead.getProperties("ftp_filepath");
				charset = DZConfigRead.getProperties("charset");
				start_row = DZConfigRead.getProperties("start_row");
			}

		}else{
			source_type=DZConfigRead.getProperties("source_type_"+mercharnum);
			address=DZConfigRead.getProperties("ftp_ip_"+mercharnum);
			local_path=DZConfigRead.getProperties("local_path_"+mercharnum);
			//fileName=DZConfigRead.getProperties("fileName_"+mercharnum);
			dz_date_format=DZConfigRead.getProperties("dz_date_format_"+mercharnum);
			dz_date_addday=DZConfigRead.getProperties("dz_date_addday_"+mercharnum);
			ftp_port=DZConfigRead.getProperties("ftp_port_"+mercharnum);
			username=DZConfigRead.getProperties("ftp_username_"+mercharnum);
			password=DZConfigRead.getProperties("ftp_password_"+mercharnum);
			remotePath=DZConfigRead.getProperties("ftp_filepath_"+mercharnum);
			charset = DZConfigRead.getProperties("charset_"+mercharnum);
			start_row = DZConfigRead.getProperties("start_row_"+mercharnum);

		}

		SimpleDateFormat sdf = new SimpleDateFormat(dz_date_format);
		Calendar calendar = Calendar.getInstance();
		if (StringHelper.isEmpty(dzDate)) {
			calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(dz_date_addday.toString()));
		} else {
			calendar.setTime(PowerDateFormat.getInstance(DateUtil.YYYYMMDD).parse(dzDate));
		}
		String filename = fileName.replace("{merchant}", mercharnum).replace("{date}", sdf.format(calendar.getTime()));
		File file=new File(local_path, filename);


		String path = local_path + filename;
		if(null!=source_type && source_type.equals("1")){
			dzInfoArray=ReadFile(path, mercharnum,dzDate,charset,start_row);
		}else if("2".equals(source_type)){
			LOG.addDebug("连接ftp取数据:{ftp_ip:"+address+",ftp_port:"+ftp_port+",ftp_remotepath:"+remotePath+",filename:"+file.getName()+"}");
			LOG.addDebug("FTP账号信息:{username:"+username+",pwd:"+password+"}");
			boolean download = false;
			int port = StringHelper.isEmpty(ftp_port) ? 21 : Integer.valueOf(ftp_port);
			try {
				download = new FtpUtil(address,port,username,password,remotePath).downFile(file);
			} catch (Exception e) {
				dzInfoArray.setRc("-1");
				dzInfoArray.setErrormsg("ftp异常");
				LOG.addError("连接ftp异常"+e);
				return dzInfoArray;
			}
			if (!download) {
				dzInfoArray.setRc("-1");
				dzInfoArray.setErrormsg("ftp上未找到对账文件"+file.getName());
				LOG.addError("ftp上未找到对账文件"+file.getName());
				return dzInfoArray;
			}
			dzInfoArray= ReadFile(path, mercharnum,dzDate,charset,start_row);
		}else{
			dzInfoArray.setRc("-1");
			dzInfoArray.setErrormsg("未获取到实现方式获取实现方式暂未开放");
			LOG.addError("未获取到实现方式获取实现方式暂未开放");
		}

		return dzInfoArray;
	}


	private DZInfoArray ReadFile(String path, String mercharnum, String dzDate,String charset,String startrow) {
		DZInfoArray  dzInfoArray=new DZInfoArray();
		File file = new File(path);
		if(!file.exists()){
			dzInfoArray.setRc("-1");
			dzInfoArray.setErrormsg(file.getName() + "文件不存在");
			dzInfoArray.setDzInfo(new DZInfo[0]);
			return dzInfoArray;
		}

		int start_row = 1;
		if(!StringHelper.isEmpty(startrow)){
			start_row = Integer.valueOf(startrow);
		}

		List<DZInfo> list=new ArrayList<DZInfo>();
		try {
			list = readCsv(path, mercharnum,start_row);


			dzInfoArray.setRc("1");
			dzInfoArray.setDzInfo( list.toArray(new DZInfo[list.size()]));
		}catch (Exception e) {
			LOG.addError("解析对账文件"+file.getName()+"异常:"+e);
		}

		return dzInfoArray;
	} 

	public DZInfo getDzinfo(String lineText){
		DZInfo dzInfo = null;
		try {
			if(!StringHelper.isEmpty(lineText)){
				String[] ss = lineText.split(",");

				if(null!=ss && ss.length>0){
					String index = ss[0];
					if(isNumeric(index)){
						dzInfo = new DZInfo();
						String termid = ss[1];
						String card_no = ss[3];
						String amount = ss[4];
						String tran_type = ss[12];
						if("消费".equals(tran_type)){
							tran_type = "S1";
						}else if ("退货".equals(tran_type)) {
							tran_type = "S3";
						}else if("消费撤销".equals(tran_type) || "消费撤消".equals(tran_type)){
							tran_type = "S2";
						}
						String refernum = ss[11];
						String tran_date = ss[13] + " " + ss[2];
				
						dzInfo.setTermId(getValue(termid));
						dzInfo.setTranCardNum(getValue(card_no));
						dzInfo.setAmount(Float.valueOf(getValue(amount)));
						dzInfo.setReferNum(getValue(refernum));
						dzInfo.setTranCode(tran_type);
						dzInfo.setTrDateTime(tran_date);
					}
				}
			}


		} catch (Exception e) {
			return null;
		}
		return dzInfo;
	}

	public static boolean isNumeric(String str){
		for (int i = 0; i < str.length(); i++){
			System.out.println(str.charAt(i));
			if (!Character.isDigit(str.charAt(i))){
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) {
		DZInfoArray  dzInfoArray=new DZInfoArray();
		dzInfoArray=	new SMXICBCDZSerivceImpl().getDZData("171351010013000", "20171225");
		DZInfo[]  d= dzInfoArray.getDzInfo();

		if(null!=d && d.length>0){
			for (int i = 0; i < d.length; i++) {
				System.out.println(d[i]);
			}
			System.out.println(d.length);
		}
		
	/*	String value =  new SMXICBCDZSerivceImpl().getValue("=\"171351010013001\"");
        System.out.println(value);*/
	}
//271-23;248

	/**
	 * Read the Excel 2003-2007
	 * @param path the path of the Excel
	 * @return
	 * @throws IOException
	 */
	public List<DZInfo> readCsv(String path,String mercharnum,int START_ROW) throws IOException {

		List<DZInfo> list = new ArrayList<DZInfo>();
		BufferedReader br = null;
		try{
			br=new BufferedReader(new InputStreamReader(new FileInputStream(path),"gbk"));  
			String line = "";
			String everyLine = "";
			DZInfo dzinfo = null;
			while ((line = br.readLine()) != null){  //读取到的内容给line变量		
				everyLine = line;
				System.out.println(everyLine);
				dzinfo = getDzinfo(everyLine);

				if(null!=dzinfo){
					list.add(dzinfo);
				}
			}
		} catch (FileNotFoundException e){
			e.printStackTrace();
		}

		return list;
	}

    public String getValue(String orgValue){
    	String newValue = null;
    	
    	if(orgValue.contains("=\"")){
    		newValue = orgValue.substring(2, orgValue.length()-1);
    	}else{
    		newValue = orgValue;
    	}
    	return newValue;
    }

}
